package com.drinks.yiniang.ui.activity.category;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.PopupWindow;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.category.CategoryGoodsAdapter;
import com.drinks.yiniang.adapter.category.SubCategoryLeftAdapter;
import com.drinks.yiniang.common.recycler.decoration.CategoryGoodsItemDecoration;
import com.drinks.yiniang.common.recycler.decoration.ItemSpacesDecoration;
import com.drinks.yiniang.common.listener.OnCategoryNavgationBarClickListener;
import com.drinks.yiniang.entity.category.CategoryGoodsJson;
import com.drinks.yiniang.entity.category.CategoryHotBrandJson;
import com.drinks.yiniang.entity.category.SubCategoryJson;
import com.drinks.yiniang.entity.comment.BannerEntity;
import com.drinks.yiniang.io.api.GoodsApiIO;
import com.drinks.yiniang.io.api.ShoppingCartApiIO;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.drinks.yiniang.ui.activity.goods.ShoppingCartActivity;
import com.drinks.yiniang.ui.activity.search.SearchGoodsActivity;
import com.drinks.yiniang.ui.activity.shop.MfrsDetailActivity;
import com.drinks.yiniang.ui.widget.layout.ScreeningCategoryMenuLayout;
import com.drinks.yiniang.ui.widget.pop.CategoryPopup;
import com.drinks.yiniang.utils.ActivityUtils;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.widget.image.RatioRoundImageView;
import com.drinks.yiniang.ui.widget.layout.ScreeningCategoryLayout;
import com.drinks.yiniang.ui.widget.nav.NavigationCategoryBarLayout;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.RecyclerUtils;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import static com.drinks.yiniang.entity.category.CategoryGoodsJson.ITEM_TYPE_CATEGORY_GOODS;
import static com.drinks.yiniang.entity.category.CategoryGoodsJson.ITEM_TYPE_CATEGORY_HOT_GOODS;

/**
 * 分类页面-包含子分类
 *
 * @author han
 * @date 2019/09/16
 */
public class CategoryActivity extends BaseTranBarActivity implements OnCategoryNavgationBarClickListener,
        ScreeningCategoryLayout.OnCategoryScreeningListener, DrawerLayout.DrawerListener, TabLayout.OnTabSelectedListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener, PopupWindow.OnDismissListener,
        AdapterView.OnItemClickListener, ScreeningCategoryMenuLayout.OnCategoryDrawerScreeningListener {

    private final String ID_STYLE_HOT_BRAND = "-1000";

    //nav
    private NavigationCategoryBarLayout nav_bar_category;
    //筛选
    private DrawerLayout drawer_category_screening;
    private ScreeningCategoryMenuLayout ll_drawer_screening;
    //销量
    private ScreeningCategoryLayout layout_category_screening;
    //子分类
    private BaseRecyclerView rcv_category_left;
    //子分类下商品
    private BaseRecyclerView rcv_category_goods;
    //分类属性
    private TabLayout tab_category_attrs;
    //banner
    private RatioRoundImageView iv_category_goods_banner;

    private CategoryPopup mCategoryPopup;

    //子分类left adapter
    private SubCategoryLeftAdapter mCategoryLeftAdapter;
    //分类商品列表
    private CategoryGoodsAdapter mGoodsAdapter;

    //tab list
    private List<SubCategoryJson.SubCategoryList> mTabList;

    //banner
    private String mBannerType;
    private String mBannerValue;

    //父分类id
    private String mCategoryId;
    //0销量 1价格 2新品 3热评
    private String mScreenType;
    //1升序 2降序
    private String mSortType;
    //-1为你推荐 0全部 >0正常
    private String mStyleId;
    //属性id
    private String mAttrsId;
    private String mMaxPrice;
    private String mMinPrice;
    //品牌ID
    private String mBrandId;
    //原产地ID
    private String mOriginId;
    //酒精度ID
    private String mAlcoholId;
    //容量
    private String mCapacity;
    //包装方式 字符串
    private String mPackType;

    private int mPages;

    @Override
    protected void initView() {
        nav_bar_category = findViewById(R.id.nav_bar_category);

        drawer_category_screening = findViewById(R.id.drawer_category_screening);

        ll_drawer_screening = drawer_category_screening.findViewById(R.id.ll_drawer_screening);
        layout_category_screening = findViewById(R.id.layout_category_screening);

        tab_category_attrs = findViewById(R.id.tab_category_attrs);

        rcv_category_left = findViewById(R.id.rcv_category_left);
        rcv_category_goods = findViewById(R.id.rcv_category_goods);

        //关闭手势侧滑打开
        drawer_category_screening.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        mCategoryId = getIntent() != null ? getIntent().getStringExtra(Constants.KeyCategoryId) : null;

        mCategoryPopup = new CategoryPopup(this);

        initCategoryLeftAdapter();
        initCategoryGoodsAdapter();
        getSubCategory();
    }

    private void initCategoryLeftAdapter() {
        rcv_category_left.setLayoutManager(new LinearLayoutManager(mContext));
        rcv_category_left.addItemDecoration(ItemSpacesDecoration.getLRTItemCountDPDecoration(12));

        mCategoryLeftAdapter = new SubCategoryLeftAdapter(mContext, new ArrayList<SubCategoryJson.SubCategoryList>());
        mCategoryLeftAdapter.setCenterEmpty(getLayoutInflater(), rcv_category_left);
        mCategoryLeftAdapter.bindToRecyclerView(rcv_category_left);
    }

    private void initCategoryGoodsAdapter() {
        mGoodsAdapter = new CategoryGoodsAdapter(mContext, new ArrayList<CategoryGoodsJson.CategoryGoodsList>());
        mGoodsAdapter.addHeaderView(getHeaderView());
        mGoodsAdapter.setHeaderAndEmpty(true);
        mGoodsAdapter.setCommonEmpty(getLayoutInflater(), rcv_category_goods);
        mGoodsAdapter.bindToRecyclerView(rcv_category_goods);

        rcv_category_goods.addItemDecoration(CategoryGoodsItemDecoration.getItemDPDecoration(10));
        rcv_category_goods.setLayoutManager(RecyclerUtils.getCategoryGoodsGridLayout(mContext, mGoodsAdapter.getData()));
    }

    //获取header
    private View getHeaderView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_category_goods_banner, (ViewGroup) rcv_category_goods.getParent(), false);

        iv_category_goods_banner = mHeaderView.findViewById(R.id.iv_category_goods_banner);

        iv_category_goods_banner.setOnClickListener(this);

        return mHeaderView;
    }

    @Override
    protected void initListener() {
        nav_bar_category.setOnNavgationBarClickListener(this);

        layout_category_screening.setOnCategoryScreeningListener(this);
        drawer_category_screening.addDrawerListener(this);
        ll_drawer_screening.setOnCategoryDrawerScreeningListener(this);
        tab_category_attrs.addOnTabSelectedListener(this);

        mCategoryLeftAdapter.setOnItemClickListener(this);
        mGoodsAdapter.setOnItemClickListener(this);
        mGoodsAdapter.setOnItemChildClickListener(this);
        mGoodsAdapter.setOnLoadMoreListener(this, rcv_category_goods);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_category_goods_banner://banner
                ActivityUtils.startActivityByAdType(mContext, mBannerType, mBannerValue);
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_category;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (drawer_category_screening.isDrawerOpen(GravityCompat.START)) {
            drawer_category_screening.closeDrawer(GravityCompat.START);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onTitleClick(View v) {
        mCategoryPopup.showCategoryListPop(nav_bar_category, mContext);
    }

    @Override
    public void onSearchClick(View v) {
        Intent intent = new Intent(mContext, SearchGoodsActivity.class);
        intent.putExtra(Constants.KeyCategoryId, mCategoryId);
        startActivity(intent);
    }

    @Override
    public void onShoppingCart(View v) {
        //购物车
        Intent intent = new Intent(mContext, ShoppingCartActivity.class);
        startActivity(intent);
    }

    @Override
    public void onCategoryScreeningClick(View v, String type, String sort) {
        if (ScreeningCategoryLayout.TYPE_SCREEN_BY_MORE.equals(type)) {
            openDrawer();
        } else {
            mScreenType = type;
            mSortType = sort;
            getGoodsList(true, true);
        }
    }

    @Override
    public void onCategoryDrawerScreening(String minPrice, String maxPrice, String packType, String origin, String alcohol, String capacity, String brand) {
        closeDrawer();

        this.mMinPrice = minPrice;
        this.mMaxPrice = maxPrice;
        this.mPackType = packType;
        this.mOriginId = origin;
        this.mAlcoholId = alcohol;
        this.mCapacity = capacity;
        this.mBrandId = brand;

        getGoodsList(true, true);

    }

    @Override
    public void onDrawerSlide(@NonNull View view, float v) {

    }

    @Override
    public void onDrawerOpened(@NonNull View view) {

    }

    @Override
    public void onDrawerClosed(@NonNull View view) {

    }

    @Override
    public void onDrawerStateChanged(int i) {

    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if (CommonUtils.isArrayIndexOutOfBounds(mTabList, tab.getPosition())) {
            return;
        }

        mAttrsId = mTabList.get(tab.getPosition()).getId();

        getGoodsList(true, true);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void onDismiss() {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //list pop item click
        mCategoryPopup.dismissPop();
        if(CommonUtils.isArrayIndexOutOfBounds(mCategoryPopup.getCategoryList(), position)) {
            return;
        }

        mCategoryId = mCategoryPopup.getCategoryList().get(position).getId();

        setNavBarCategoryName(mCategoryPopup.getCategoryList().get(position).getName());

        getGoodsList(true, true);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter instanceof SubCategoryLeftAdapter) {
            mCategoryLeftAdapter.setCurrentChoosePos(position);

            SubCategoryJson.SubCategoryList data = mCategoryLeftAdapter.getItem(position);

            if (data == null) {
                return;
            }

            if (ID_STYLE_HOT_BRAND.equals(data.getId())) {//获取热门品牌
                mStyleId = null;
                clearGoodsListData(true);
                getHotBrandList();
            } else {
                mStyleId = data.getId();
                if(tab_category_attrs.getTabCount() > 0 && !tab_category_attrs.getTabAt(0).isSelected()) {
                    tab_category_attrs.getTabAt(0).select();
                } else {
                    getGoodsList(true, true);
                }
            }
        } else {
            Intent mIntent;

            CategoryGoodsJson.CategoryGoodsList data = mGoodsAdapter.getItem(position);

            if (data == null) {
                return;
            }

            switch (adapter.getItemViewType(adapter.getHeaderLayoutCount() + position)) {
                case ITEM_TYPE_CATEGORY_GOODS://商品
                    mIntent = new Intent(mContext, GoodsDetailsActivity.class);
                    mIntent.putExtra(Constants.KeyGoodsId, data.getId());
                    startActivity(mIntent);
                    break;
                case ITEM_TYPE_CATEGORY_HOT_GOODS://热门品牌
                    mIntent = new Intent(mContext, MfrsDetailActivity.class);
                    mIntent.putExtra(Constants.KeyId, data.getTempHotBrand().getId());
                    startActivity(mIntent);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        CategoryGoodsJson.CategoryGoodsList data = mGoodsAdapter.getItem(position);

        if (data == null) {
            return;
        }

        if(adapter instanceof CategoryGoodsAdapter) {
            switch (adapter.getItemViewType(adapter.getHeaderLayoutCount() + position)) {
                case ITEM_TYPE_CATEGORY_GOODS://商品
                    if (view.getId() == R.id.iv_category_goods_add_cart) addToCart(data.getId());
                    break;
                default:
                    break;
            }
        }
    }

    private void clearGoodsListData(boolean isClear) {
        if(isClear) {
            mGoodsAdapter.getData().clear();
            mGoodsAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onLoadMoreRequested() {
        GoodsApiIO.getInstance().getCategoryGoodsList(mCategoryId, mScreenType, mSortType, mStyleId, mAttrsId, mMaxPrice, mMinPrice,
                mBrandId, mOriginId, mAlcoholId, mCapacity, mPackType, mPages, new APIRequestCallback<CategoryGoodsJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(CategoryGoodsJson res) {
                        if (mGoodsAdapter == null) {
                            return;
                        }

                        mPages++;

                        mGoodsAdapter.addData(res.getData().getData());

                        if (CommonUtils.isHasMoreData(res.getData().getData())) {
                            mGoodsAdapter.loadMoreComplete();
                        } else {
                            mGoodsAdapter.loadMoreEnd();
                        }
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                        mGoodsAdapter.loadMoreFail();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    //获取商品列表
    private void getGoodsList(boolean isShowLoading, boolean isClearListData) {
        if(isShowLoading) {
            showLoadingDialog();
        }

        clearGoodsListData(isClearListData && !CommonUtils.isEmptyList(mGoodsAdapter.getData()));

        mPages = 1;

        GoodsApiIO.getInstance().getCategoryGoodsList(mCategoryId, mScreenType, mSortType, mStyleId, mAttrsId, mMaxPrice, mMinPrice,
                mBrandId, mOriginId, mAlcoholId, mCapacity, mPackType, mPages, new APIRequestCallback<CategoryGoodsJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(CategoryGoodsJson res) {
                        if (mGoodsAdapter == null) {
                            return;
                        }

                        mPages++;

                        mGoodsAdapter.getData().clear();
                        mGoodsAdapter.addData(res.getData().getData());

                        if (CommonUtils.isHasMoreData(res.getData().getData())) {
                            mGoodsAdapter.loadMoreComplete();
                        } else {
                            mGoodsAdapter.loadMoreEnd();
                        }
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                        mGoodsAdapter.loadMoreFail();
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    //获取热门品牌
    private void getHotBrandList() {
        showLoadingDialog();

        GoodsApiIO.getInstance().getCategoryHotBrandList(mCategoryId, new APIRequestCallback<CategoryHotBrandJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CategoryHotBrandJson res) {
                if (mGoodsAdapter == null) {
                    return;
                }

                List<CategoryGoodsJson.CategoryGoodsList> ls = new ArrayList<>();
                CategoryGoodsJson.CategoryGoodsList data = null;

                for (int i = 0; i < res.getData().size(); i++) {
                    data = new CategoryGoodsJson.CategoryGoodsList();
                    data.setItemType(ITEM_TYPE_CATEGORY_HOT_GOODS);
                    data.setTempHotBrand(res.getData().get(i));
                    ls.add(data);
                }

                mGoodsAdapter.getData().clear();
                mGoodsAdapter.addData(ls);
                mGoodsAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mGoodsAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取子分类列表
    private void getSubCategory() {
        if (StringUtils.isEmpty(mCategoryId)) {
            ToastUtils.showShort(R.string.text_the_category_not_exist);
            return;
        }

        showLoadingDialog();

        GoodsApiIO.getInstance().getSubCategory(mCategoryId, new APIRequestCallback<SubCategoryJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(SubCategoryJson res) {
                setNavBarCategoryName(res.getData().getCategory().getName());
                mCategoryPopup.setCategorytList(res.getData().getCategory_list());
                setLeftData(res.getData().getStyles());
                setAttrsData(res.getData().getAttributes());
                setBannerData(res.getData().getBanners());
                //drawer data
                ll_drawer_screening.addAlcohols(res.getData().getAlcohols());
                ll_drawer_screening.addPackmethods(res.getData().getPackage_methods());
                ll_drawer_screening.addOrigins(res.getData().getOrigins());
                ll_drawer_screening.addCapacitys(res.getData().getCapacity());
                ll_drawer_screening.addBrands(res.getData().getBrands());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //左侧风格列表
    private void setLeftData(List<SubCategoryJson.SubCategoryList> styleList) {
        if (CommonUtils.isEmptyList(styleList)) {
            return;
        }

        //默认第一个
        mStyleId = styleList.get(0).getId();

        SubCategoryJson.SubCategoryList hotBrand = new SubCategoryJson.SubCategoryList();
        hotBrand.setId(ID_STYLE_HOT_BRAND);
        hotBrand.setName(getString(R.string.text_hot_brand));

        styleList.add(hotBrand);

        mCategoryLeftAdapter.getData().clear();
        mCategoryLeftAdapter.addData(styleList);
        mCategoryLeftAdapter.setCurrentChoosePos(0);
    }

    //右侧横向属性tab列表
    private void setAttrsData(List<SubCategoryJson.SubCategoryList> attrsList) {
        if (CommonUtils.isEmptyList(attrsList)) {
            attrsList = new ArrayList<>();
        }

        if (mTabList == null) {
            mTabList = new ArrayList<>();
        }

        SubCategoryJson.SubCategoryList allAttrs = new SubCategoryJson.SubCategoryList();
        allAttrs.setId("0");
        allAttrs.setName(getString(R.string.text_all));

        mTabList.clear();
        mTabList.add(allAttrs);
        mTabList.addAll(attrsList);

        tab_category_attrs.removeAllTabs();

        for (int i = 0; i < mTabList.size(); i++) {
            tab_category_attrs.addTab(tab_category_attrs.newTab().setText(mTabList.get(i).getName()));
        }
    }

    //设置banner数据
    private void setBannerData(List<BannerEntity> bannerList) {
        if(iv_category_goods_banner.getParent() instanceof FrameLayout) {
            if(!CommonUtils.isEmptyList(bannerList)) {
                mBannerType = bannerList.get(0).getType();
                mBannerValue = bannerList.get(0).getValue();

                ((FrameLayout) iv_category_goods_banner.getParent()).setVisibility(View.VISIBLE);

                GlideUtils.loadBannerImage(mContext, iv_category_goods_banner, bannerList.get(0).getCover_url());
            } else {
                ((FrameLayout) iv_category_goods_banner.getParent()).setVisibility(View.GONE);
            }
        }
    }

    private void addToCart(String goodsId) {
        showLoadingDialog();

        ShoppingCartApiIO.getInstance().addToShopCart(goodsId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                ToastUtils.showShort(getString(R.string.text_add_success));
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void closeDrawer() {
        if (drawer_category_screening.isDrawerOpen(GravityCompat.END)) {
            drawer_category_screening.closeDrawer(GravityCompat.END);
        }
    }

    private void openDrawer() {
        if (!drawer_category_screening.isDrawerOpen(GravityCompat.END)) {
            drawer_category_screening.openDrawer(GravityCompat.END);
        }
    }

    //设置分类nav bar名称
    private void setNavBarCategoryName(String name) {
        if(StringUtils.isEmpty(name)) {
            return;
        }

        nav_bar_category.setNavBarTitle(name);
    }
}
